package com.yubb.platform.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yubb.common.annotation.PlatformDataScope;
import com.yubb.common.constant.UserConstants;
import com.yubb.common.core.domain.Ztree;
import com.yubb.common.core.domain.platform.PlatformDept;
import com.yubb.common.core.domain.platform.dto.PlatformDeptDTO;
import com.yubb.common.core.domain.platform.dto.PlatformRoleDTO;
import com.yubb.common.core.domain.platform.vo.PlatformDeptVO;
import com.yubb.common.exception.BusinessException;
import com.yubb.common.utils.StringUtils;
import com.yubb.common.utils.bean.DozerUtils;
import com.yubb.platform.mapper.PlatformDeptMapper;
import com.yubb.platform.service.IPlatformDeptService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;

import static com.yubb.common.constant.Constants.DEL_FLAG_DEL;
import static com.yubb.common.constant.Constants.DEL_FLAG_NORMAL;

/**
 * @Description 平台部门接口实现
 * @Author zhushuyong
 * @Date 2021/7/15 22:39
 * @since:
 * @copyright: 版权所有2021 开源组织 gitee(https://gitee.com/jinzheyi)作者：朱述勇<br/>
 * GitHub(https://github.com/jinzheyi)作者：朱述勇 。
 */
@Slf4j
@Service
public class PlatformDeptServiceImpl extends ServiceImpl<PlatformDeptMapper, PlatformDept> implements IPlatformDeptService {

    @Autowired
    private PlatformDeptMapper deptMapper;

    /**
     * 查询部门管理数据
     *
     * @param dept 部门信息
     * @return 部门信息集合
     */
    @Override
    @PlatformDataScope(deptAlias = "d")
    public List<PlatformDeptVO> selectDeptList(PlatformDeptDTO dept) {
        return deptMapper.selectDeptList(dept);
    }

    /**
     * 查询部门管理树
     *
     * @param dept 部门信息
     * @return 所有部门信息
     */
    @Override
    @PlatformDataScope(deptAlias = "d")
    public List<Ztree> selectDeptTree(PlatformDeptDTO dept) {
        List<PlatformDeptVO> deptList = deptMapper.selectDeptList(dept);
        List<Ztree> ztrees = initZtree(deptList);
        return ztrees;
    }

    /**
     * 查询部门管理树（排除下级）
     *
     * @param dept 部门信息
     * @return 所有部门信息
     */
    @Override
    @PlatformDataScope(deptAlias = "d")
    public List<Ztree> selectDeptTreeExcludeChild(PlatformDeptDTO dept)
    {
        String deptId = dept.getId();
        List<PlatformDeptVO> deptList = deptMapper.selectDeptList(dept);
        Iterator<PlatformDeptVO> it = deptList.iterator();
        while (it.hasNext())
        {
            PlatformDeptVO d = (PlatformDeptVO) it.next();
            if (d.getId().equals(deptId)
                    || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), deptId + ""))
            {
                it.remove();
            }
        }
        List<Ztree> ztrees = initZtree(deptList);
        return ztrees;
    }

    /**
     * 根据角色ID查询部门（数据权限）
     *
     * @param role 角色对象
     * @return 部门列表（数据权限）
     */
    @Override
    public List<Ztree> roleDeptTreeData(PlatformRoleDTO role)
    {
        String roleId = role.getId();
        List<Ztree> ztrees = new ArrayList<Ztree>();
        List<PlatformDeptVO> deptList = selectDeptList(new PlatformDeptDTO());
        if (StringUtils.isNotNull(roleId))
        {
            List<String> roleDeptList = deptMapper.selectRoleDeptTree(roleId);
            ztrees = initZtree(deptList, roleDeptList);
        }
        else
        {
            ztrees = initZtree(deptList);
        }
        return ztrees;
    }

    /**
     * 对象转部门树
     *
     * @param deptList 部门列表
     * @return 树结构列表
     */
    public List<Ztree> initZtree(List<PlatformDeptVO> deptList)
    {
        return initZtree(deptList, null);
    }

    /**
     * 对象转部门树
     *
     * @param deptList 部门列表
     * @param roleDeptList 角色已存在菜单列表
     * @return 树结构列表
     */
    public List<Ztree> initZtree(List<PlatformDeptVO> deptList, List<String> roleDeptList)
    {

        List<Ztree> ztrees = new ArrayList<Ztree>();
        boolean isCheck = StringUtils.isNotNull(roleDeptList);
        for (PlatformDeptVO dept : deptList)
        {
            if (UserConstants.DEPT_NORMAL.equals(dept.getStatus()))
            {
                Ztree ztree = new Ztree();
                ztree.setId(dept.getId());
                ztree.setpId(dept.getParentId());
                ztree.setName(dept.getDeptName());
                ztree.setTitle(dept.getDeptName());
                if (isCheck)
                {
                    ztree.setChecked(roleDeptList.contains(dept.getId() + dept.getDeptName()));
                }
                ztrees.add(ztree);
            }
        }
        return ztrees;
    }

    /**
     * 查询部门人数
     *
     * @param parentId 部门ID
     * @return 结果
     */
    @Override
    public Long selectDeptCount(String parentId)
    {
        PlatformDeptDTO dept = PlatformDeptDTO.builder().parentId(parentId).build();
        return deptMapper.selectCount(new LambdaQueryWrapper<PlatformDept>()
                .eq(PlatformDept::getDelFlag, DEL_FLAG_NORMAL)
                .eq(StringUtils.isNotBlank(dept.getId()), PlatformDept::getId, dept.getId())
                .eq(StringUtils.isNotBlank(dept.getParentId()), PlatformDept::getParentId, dept.getParentId()));
    }

    /**
     * 查询部门是否存在用户
     *
     * @param deptId 部门ID
     * @return 结果 true 存在 false 不存在
     */
    @Override
    public boolean checkDeptExistUser(String deptId)
    {
        long result = deptMapper.selectCount(Wrappers.query(PlatformDept.builder()
                .id(deptId)
                .delFlag(DEL_FLAG_NORMAL).build()));
        return result > 0 ? true : false;
    }

    /**
     * 删除部门管理信息
     *
     * @param deptId 部门ID
     * @return 结果
     */
    @Override
    public int deleteDeptById(String deptId)
    {
        return deptMapper.update(PlatformDept.builder().delFlag(DEL_FLAG_DEL).build(),
                Wrappers.query(PlatformDept.builder().id(deptId).build()));
    }

    /**
     * 新增保存部门信息
     *
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    public int insertDept(PlatformDeptDTO dept)
    {
        PlatformDeptVO info = deptMapper.selectDeptById(dept.getParentId());
        // 如果父节点不为"正常"状态,则不允许新增子节点
        if (!UserConstants.DEPT_NORMAL.equals(info.getStatus()))
        {
            throw new BusinessException("部门停用，不允许新增");
        }
        dept.setAncestors(info.getAncestors() + "," + dept.getParentId());
        return deptMapper.insert(DozerUtils.copyProperties(dept, PlatformDept.class));
    }

    /**
     * 修改保存部门信息
     *
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateDept(PlatformDeptDTO dept)
    {
        PlatformDeptVO newParentDept = deptMapper.selectDeptById(dept.getParentId());
        PlatformDeptVO oldDept = selectDeptById(dept.getId());
        if (StringUtils.isNotNull(newParentDept) && StringUtils.isNotNull(oldDept))
        {
            String newAncestors = newParentDept.getAncestors() + "," + newParentDept.getId();
            String oldAncestors = oldDept.getAncestors();
            dept.setAncestors(newAncestors);
            updateDeptChildren(dept.getId(), newAncestors, oldAncestors);
        }
        int result = deptMapper.updateById(DozerUtils.copyProperties(dept, PlatformDept.class));
        if (UserConstants.DEPT_NORMAL.equals(dept.getStatus()))
        {
            // 如果该部门是启用状态，则启用该部门的所有上级部门
            updateParentDeptStatus(dept);
        }
        return result;
    }

    /**
     * 修改该部门的父级部门状态
     *
     * @param dept 当前部门
     */
    private void updateParentDeptStatus(PlatformDeptDTO dept)
    {
        String updateBy = dept.getUpdateBy();
        dept = DozerUtils.copyProperties(deptMapper.selectDeptById(dept.getId()), PlatformDeptDTO.class);
        dept.setUpdateBy(updateBy);
        deptMapper.updateDeptStatus(dept);
    }

    /**
     * 修改子元素关系
     *
     * @param deptId 被修改的部门ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    public void updateDeptChildren(String deptId, String newAncestors, String oldAncestors)
    {
        List<PlatformDeptVO> children = deptMapper.selectChildrenDeptById(deptId);
        for (PlatformDeptVO child : children)
        {
            child.setAncestors(child.getAncestors().replace(oldAncestors, newAncestors));
        }
        if (children.size() > 0)
        {
            deptMapper.updateDeptChildren(BeanUtil.copyToList(children, PlatformDeptDTO.class));
        }
    }

    /**
     * 根据部门ID查询信息
     *
     * @param deptId 部门ID
     * @return 部门信息
     */
    @Override
    public PlatformDeptVO selectDeptById(String deptId)
    {
        return deptMapper.selectDeptById(deptId);
    }

    /**
     * 根据ID查询所有子部门（正常状态）
     *
     * @param deptId 部门ID
     * @return 子部门数
     */
    @Override
    public int selectNormalChildrenDeptById(String deptId)
    {
        return deptMapper.selectNormalChildrenDeptById(deptId);
    }

    /**
     * 校验部门名称是否唯一
     *
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    public String checkDeptNameUnique(PlatformDeptDTO dept)
    {
        String deptId = StringUtils.isIdNull(dept.getId());
        Optional<PlatformDept> info = deptMapper.selectList(Wrappers.query(PlatformDept.builder()
                .deptName(dept.getDeptName())
                .parentId(dept.getParentId()).build())).stream().findFirst();
        if (info.isPresent() && !deptId.equals(info.get().getId()))
        {
            return UserConstants.DEPT_NAME_NOT_UNIQUE;
        }
        return UserConstants.DEPT_NAME_UNIQUE;
    }

}
